#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>

#include "proxytest.h"
#include "thread_control.h"

static sem_t *sem_ctl;
static sem_t *sem_wat;

static char* name_ctl = "aaaa";
static char* name_wait = "bbbb";

typedef struct __thread_control_arg_t
{
	void*(*func)(void*);
	void* arg;
} thread_control_arg_t;

static void* thread_control_real_thread(void* tc_arg)
{
	pthread_detach(pthread_self());

	thread_control_arg_t* x_arg=(thread_control_arg_t*)tc_arg;


	sem_post(sem_wat);
	sem_wait(sem_ctl);

	x_arg->func(x_arg->arg);

	free(tc_arg);

	sem_post(sem_ctl);
	sem_wait(sem_wat);
	return NULL;
}

int thread_control_init(int max_thread)
{
	sem_unlink(name_ctl);
	sem_unlink(name_wait);

	sem_ctl=sem_open(name_ctl, O_CREAT, 0777,max_thread);
	sem_wat=sem_open(name_wait, O_CREAT, 0777,0);

	if(sem_ctl==SEM_FAILED||sem_wat==SEM_FAILED)
	{
		printf("[error] sem_open\n");
		return -1;
	}
	return 0;
}

int thread_control_create(void*(*func)(void*),void* arg)
{
	thread_control_arg_t *tc_arg;
	tc_arg=(thread_control_arg_t*)malloc(sizeof(thread_control_arg_t));
	tc_arg->func=func;
	tc_arg->arg=arg;


	pthread_t tid;
	pthread_create(&tid,NULL,thread_control_real_thread,tc_arg);


	return 0;
}


int thread_control_wait(void)
{
	int wat;
	for(wat=1;wat>0;sem_getvalue(sem_wat,&wat))
	{
		sleep(1);
	}
	return 0;
}





int thread_control_clean()
{
	sem_unlink(name_ctl);
	sem_unlink(name_wait);
	sem_close(sem_ctl);
	sem_close(sem_wat);
	return 0;
}







